package com.gfxy.modules.items.controller;

import java.io.InputStream;
import java.io.PushbackInputStream;
import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gfxy.modules.common.entity.MemberList;
import com.gfxy.modules.common.service.IMemberListService;
import com.gfxy.modules.excel.ExcelUtil;
import com.gfxy.modules.excel.TemplateUtil;
import com.gfxy.modules.items.entity.Xss;
import com.gfxy.modules.items.service.DictTranslater;
import com.gfxy.modules.items.vo.KssMemberPage;
import com.gfxy.modules.items.vo.XssPage;
import com.gfxy.modules.system.service.ISysDepartService;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import com.gfxy.modules.items.entity.Kss;
import com.gfxy.modules.items.vo.KssPage;
import com.gfxy.modules.items.service.IKssService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 课时数
 * @Author: jeecg-boot
 * @Date:   2023-12-28
 * @Version: V1.0
 */
@Api(tags="课时数")
@RestController
@RequestMapping("/items/kss")
@Slf4j
public class KssController {
	@Autowired
	private IKssService kssService;

	 @Autowired
	 private IMemberListService memberListService;

	 @Autowired
	 private DictTranslater dictTranslater;

	 @Autowired
	 private TemplateUtil templateUtil;

	 @Autowired
	 private ISysDepartService departService;
	/**
	 * 分页列表查询
	 *
	 * @param date
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "课时数-分页列表查询")
	@ApiOperation(value="课时数-分页列表查询", notes="课时数-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(@RequestParam(name="date")  String date,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {

		IPage<KssMemberPage> pageList = kssService.selectListPage(date, pageNo, pageSize);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param kssPage
	 * @return
	 */
	@AutoLog(value = "课时数-添加")
	@ApiOperation(value="课时数-添加", notes="课时数-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody KssPage kssPage) {
		Kss kss = new Kss();
		BeanUtils.copyProperties(kssPage, kss);
		kssService.saveMain(kss, kssPage.getMemberListList());
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param kssPage
	 * @return
	 */
	@AutoLog(value = "课时数-编辑")
	@ApiOperation(value="课时数-编辑", notes="课时数-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody KssPage kssPage) {
		Kss kss = new Kss();
		BeanUtils.copyProperties(kssPage, kss);
		Kss kssEntity = kssService.getById(kss.getId());
		if(kssEntity==null) {
			return Result.error("未找到对应数据");
		}
		kssService.updateMain(kss, kssPage.getMemberListList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "课时数-通过id删除")
	@ApiOperation(value="课时数-通过id删除", notes="课时数-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		kssService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "课时数-批量删除")
	@ApiOperation(value="课时数-批量删除", notes="课时数-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.kssService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "课时数-通过id查询")
	@ApiOperation(value="课时数-通过id查询", notes="课时数-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		Kss kss = kssService.getById(id);
		if(kss==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(kss);

	}
	

    /**
    * 导出excel
    *
    * @param request
    * @param id
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, String id) throws NoSuchFieldException {

		Kss kss = this.kssService.getById(id);
		String date = kss.getDate();

		List<MemberList> memberLists = memberListService.selectByItemId(id);

		String depName = dictTranslater.getDictValue(Kss.class, "orgId", String.valueOf(kss.getOrgId()));
		List<String> firstLine = new ArrayList<>();
		firstLine.add(depName);
		firstLine.add("课时总数：");
		firstLine.add(String.valueOf(kss.getClasstimeNum()));
		firstLine.add("总积分：");
		firstLine.add(String.valueOf(kss.getTotalScore()));


		List<String> title = new ArrayList<>();
		title.add("时间");
		title.add("教工编号");
		title.add("姓名");
		title.add("积分");



		List<List<String>> contents = new ArrayList<>();

		for (MemberList memberList : memberLists) {
			List<String> content = new ArrayList<>();
			content.add(kss.getDate());
			content.add(memberList.getTeacherId());
			content.add(dictTranslater.getDictValue(MemberList.class, "teacherId", String.valueOf(memberList.getTeacherId())));
			content.add(String.valueOf(memberList.getScore()));
			contents.add(content);
		}


		ModelAndView mv = new ModelAndView(new XssExcelView());
		mv.addObject(XssExcelView.FILE_NAME, "标准输出-"+date);
		mv.addObject(XssExcelView.FIRSTLINE, firstLine);
		mv.addObject(XssExcelView.TITLE, title);
		mv.addObject(XssExcelView.CONTENT, contents);
		return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {

				String id = request.getParameter("id");
				Kss kss = this.kssService.getById(id);

				InputStream inputStream = file.getInputStream();
				if (!(inputStream).markSupported()) {
					inputStream = new PushbackInputStream(inputStream, 8);
				}
				Workbook book = WorkbookFactory.create(inputStream);
				Sheet sheet = book.getSheetAt(0);
				List<String> errorMessage = new ArrayList<>();


				List<MemberList> memberLists =  new ArrayList<>();
				double total = 0.0;
				for (int i = 2; i <= sheet.getLastRowNum(); i++) {
					Row row = sheet.getRow(i);

					String teacherId = ExcelUtil.formatCell(row.getCell(1));
					Double score = Double.parseDouble(ExcelUtil.formatCell(row.getCell(3)));
					total = total + score;

					MemberList memberList = new MemberList();
					memberList.setDate(kss.getDate());
					memberList.setScore(score);
					memberList.setItemValue(kss.getItemValue());
					memberList.setTeacherId(teacherId);
					memberList.setIsCustom(1);
					memberList.setOrgId(kss.getOrgId());
					memberList.setRanked(i-1);

					memberLists.add(memberList);
				}


				if(kss.getTotalScore().doubleValue() < total){

					errorMessage.add("总积分超过规定总分，请检查!");
					throw new Exception("总积分超过规定总分，请检查!");
				} else {

					this.kssService.updateMain(kss,memberLists);
				}


			} catch (Exception e) {
				log.error(e.getMessage(),e);
				return Result.error("文件导入失败:"+e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.OK("文件导入失败！");
    }


	 @GetMapping(value = "/getTotalScore")
	 public Result<?> getTotalScore(@RequestParam(name="classtimeNum", defaultValue="0")  Integer classtimeNum,
									HttpServletRequest req) {

		 Kss kss = new Kss();
		 kss.setClasstimeNum(classtimeNum);
		 Double result = this.kssService.getTotalScore(kss);
		 return Result.OK(result);
	 }

	 @GetMapping(value = "/getMemberListByOrgId")
	 public Result<?> getMemberListByOrgId(@RequestParam(name="orgId")  String orgId,
										   HttpServletRequest req) {
		 List<MemberList> memberLists = this.memberListService.getMemberListByOrgId(orgId);
		 return Result.OK(memberLists);
	 }

	 @AutoLog(value = "成员列表通过主表ID查询")
	 @ApiOperation(value="成员列表主表ID查询", notes="成员列表-通主表ID查询")
	 @GetMapping(value = "/queryMemberListByMainId")
	 public Result<?> queryMemberListListByMainId(@RequestParam(name="id",required=true) String id) {
		 List<MemberList> memberListList = memberListService.selectByItemId(id);
		 return Result.OK(memberListList);
	 }
}
